/****************************************************
          File Name:permisson.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 21 Feb 2015 03:36:47 PM CST
*****************************************************/

#include "pisces_process.h"
#include <pwd.h>

int check(struct perm *pm, const char *name)
{
    struct passwd *pwd;

    errno = 0;
    pwd = getpwnam(name);
    if (pwd == NULL) {
        if (errno) {
            pisces_log(P_LOG_ERR, "%s", strerror(errno));
            exit(1);
        } else
            return -1;
    }
    pm->uid = pwd->pw_uid;
    pm->gid = pwd->pw_gid;
    return 0;
}

void new_user(struct perm *pm, const char *name)
{
    /* run script to create a user without home, default is 'pisces' */
    char pattern[128] = "useradd -r -s /bin/false ";
    strcat(pattern, name);
    pattern[strlen(pattern)] = '\n';
    if (system(pattern) == -1) {        /* create user */
        pisces_log(P_LOG_ERR, "%s", strerror(errno));
        exit(1);
    }
    if (check(pm, name) == -1)
        exit(1);
}

void pisces_drop_privilige(void)
{
#if defined(__linux__)
    char *user = "pisces";
    struct perm pm;

    if (check(&pm, user) != 0)
        new_user(&pm, user);
    /* change gid before drop privilege */
    setregid(pm.gid, pm.gid);
    setreuid(pm.uid, pm.uid);
#endif
}
